package com.gree.flowable.app.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gree.flowable.app.mapper.FlwFormNodesetMapper;
import com.gree.flowable.app.mapper.FormInfoMapper;
import com.gree.flowable.app.mapper.FormModelMapper;
import com.gree.flowable.app.mapper.plus.FlwFormNodesetService;
import com.gree.flowable.app.pojo.form.FlwFormNodeset;
import com.gree.flowable.app.pojo.form.FormInfo;
import com.gree.flowable.app.pojo.form.FormModel;
import com.gree.flowable.app.pojo.vo.FlowElementVO;
import com.gree.flowable.app.pojo.vo.ReturnVO;
import com.gree.flowable.app.services.IFlowableBpmnModelService;
import com.gree.flowable.app.services.IFlwFormNodeSetService;
import com.gree.flowable.app.services.IFormInfoService;
import com.gree.flowable.app.tools.constants.ReturnCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author ：180849
 * @date ：Created in 2021/4/14 10:20
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Service
public class IFlwFormNodeSetServiceImpl implements IFlwFormNodeSetService {

    @Autowired
    private FlwFormNodesetMapper flwFormNodeSetMapper;

    @Autowired
    private FlwFormNodesetService formNodesetService;

    @Autowired
    private IFlowableBpmnModelService iFlowableBpmnModelService;

    @Autowired
    private IFormInfoService iFormInfoService;

    @Autowired
    private FormInfoMapper formInfoMapper;

    @Autowired
    private FormModelMapper formModelMapper;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Override
    public ReturnVO addFormNode(String processKey, String formId) {
        ReturnVO<Integer> result = null;
        //获取流程节点
        ReturnVO<List<FlowElementVO>> fLowElementByProceDefKey = iFlowableBpmnModelService.getFLowElementByProceDefKey(processKey);
        List<FlowElementVO> flowNodeList = fLowElementByProceDefKey.getData();
        JSONObject jsonObject = new JSONObject();
        List<FlwFormNodeset> formNodeList = new LinkedList<>();
        //根据formId获取表单项
        ReturnVO<List<FormModel>> formFieldByFormId = iFormInfoService.getFormFieldByFormId(formId);
        if (!"200".equals(formFieldByFormId.getCode())) {
            return result = new ReturnVO<>(ReturnCode.FAIL, "添加失败" + formFieldByFormId.getMsg());
        } else {
            for (FlowElementVO flowElementVO : flowNodeList) {
                FlwFormNodeset flwFormNodeSet = new FlwFormNodeset();
                //组装表单与模型关联的实体
                String node = flowElementVO.getElementId();
                if ("S000".equals(node) || "S999".equals(node)) {
                    continue;
                }
                flwFormNodeSet.setElementId(node);
                flwFormNodeSet.setProcessKey(processKey);
                flwFormNodeSet.setFormId(formId);
                List<FormModel> formInfoList = formFieldByFormId.getData();
                for (FormModel formModel : formInfoList) {
                    if ("S001".equals(node)) {
                        jsonObject.put(formModel.getFields(), 2);
                    } else {
                        jsonObject.put(formModel.getFields(), 1);
                    }
                }
                flwFormNodeSet.setFormDesc(jsonObject.toString());
                formNodeList.add(flwFormNodeSet);
            }
        }
        boolean b = formNodesetService.saveBatch(formNodeList);
//        boolean c = formNodesetService.saveOrUpdateBatch(formNodeList);
//        Integer integer = flwFormNodeSetMapper.addFormNode(formNodeList);
        result = new ReturnVO<>(ReturnCode.SUCCESS, "插入成功", 1);
        return result;
    }

    @Override
    public ReturnVO updateFormNode(String processKey, String formId) {
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        ReturnVO result = null;
        try {
            ReturnVO delResult = deleteFormNode(processKey, formId);
            if ("201".equals(delResult.getCode())) {
                new Exception("数据更新失败" + delResult.getMsg());
            }
            ReturnVO addResult = addFormNode(processKey, formId);
            if ("201".equals(addResult.getCode())) {
                new Exception("数据更新失败" + addResult.getMsg());
            }
            dataSourceTransactionManager.commit(transactionStatus);
            result = new ReturnVO(ReturnCode.SUCCESS, "数据更新成功", addResult.getData());
        } catch (Exception e) {
            dataSourceTransactionManager.rollback(transactionStatus);
            result = new ReturnVO(ReturnCode.FAIL, e.getMessage().toString());
        }

        return result;
    }

    /**
     * 解除模型与表单关系 添加formid条件
     *
     * @param processKey 流程关键字
     * @param formId     表单id
     * @return
     */
    @Override
    public ReturnVO deleteFormNode(String processKey, String formId) {
        QueryWrapper<FlwFormNodeset> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.lambda().eq(FlwFormNodeset::getProcessKey, processKey).eq(FlwFormNodeset::getFormId, formId);
        int total = flwFormNodeSetMapper.delete(deleteWrapper);
        ReturnVO<Integer> result = null;
        if (total > 0) {
            result = new ReturnVO<>(ReturnCode.SUCCESS, "删除成功", total);
        } else {
            result = new ReturnVO<>(ReturnCode.FAIL, "解除失败", total);
        }
        return result;
    }

    /**
     * 查询各个表单项的状态
     *
     * @param processKey 流程关键字
     * @param elementId  流程节点
     * @return
     */
    @Override
    public ReturnVO queryByProcessAndNode(String processKey, String elementId, Integer formType) {
        ReturnVO result = null;
        List<Map> resultList = new LinkedList<>();
        //获取流程中单个节点的表单项状态

        String formId = flwFormNodeSetMapper.getFormIdByTypeAndProcessKey(processKey, formType);
        QueryWrapper<FormModel> formModelWrapper = new QueryWrapper<>();
        formModelWrapper.lambda().eq(FormModel::getFormId, formId).orderByAsc(FormModel::getSort);
        List<FormModel> formModelList = formModelMapper.selectList(formModelWrapper);

        //获取本节点中组件的信息
        //通过formid再info表中查询那些是主表那些是明细表
        QueryWrapper<FlwFormNodeset> flowNodeWrapper = new QueryWrapper<>();
        flowNodeWrapper.lambda().eq(FlwFormNodeset::getProcessKey, processKey)
                .eq(FlwFormNodeset::getElementId, elementId)
                .eq(FlwFormNodeset::getFormId,formId);
        FlwFormNodeset formNodeset = flwFormNodeSetMapper.selectOne(flowNodeWrapper);

        for (FormModel formModel : formModelList) {
            Map<String, Object> dataMap = new HashMap<>();
            String field = formModel.getFields();
            dataMap.put("field", field);
            dataMap.put("label", formModel.getLabel());
            dataMap.put("sort", formModel.getSort());
            JSONObject formDescJson = (JSONObject)JSON.parse(formNodeset.getFormDesc());
            dataMap.put("state",formDescJson.get(field));
            resultList.add(dataMap);
        }
//        String IformId = "";
//        for (FlwFormNodeset flwFormNodeset : formNodesetList) {
//
//            String formId = flwFormNodeset.getFormId();
//            String formDesc = flwFormNodeset.getFormDesc();
//            JSONObject formDescJson = (JSONObject) JSON.parse(formDesc);
//            //查询是主表还是从表
//            QueryWrapper<FormInfo> formInfoWrapper = new QueryWrapper<>();
//            formInfoWrapper.lambda().eq(FormInfo::getFormId,formId);
//            FormInfo formInfo = formInfoMapper.selectOne(formInfoWrapper);
//            Integer formTypes = formInfo.getFormType();
//            //获取表单项详细信息
//            QueryWrapper<FormModel> formModelWrapper = new QueryWrapper<>();
//            formModelWrapper.lambda().eq(FormModel::getFormId,formId);
//            List<FormModel> formModelList = formModelMapper.selectList(formModelWrapper);
//            //组装返回值数据
//            if (formType.equals(formTypes)){
//                IformId = formId;
//                for (FormModel formModel : formModelList) {
//                    Map<String,Object> dataMap = new HashMap<>();
//                    String field = formModel.getFields();
//                    dataMap.put("field",field);
//                    dataMap.put("label",formModel.getLabel());
//                    dataMap.put("sort",formModel.getSort());
//                    dataMap.put("state",formDescJson.get(field));
//                    resultList.add(dataMap);
//                }
//            }
//
//        }


        if (resultList.size() > 0) {
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("list", resultList);
            resultMap.put("formId", formId);
            result = new ReturnVO(ReturnCode.SUCCESS, "查询成功", resultMap);
        } else {
            result = new ReturnVO(ReturnCode.SUCCESS, "查询失败", null);
        }
        return result;
    }

    @Override
    public ReturnVO updateFieldNodeState(String processKey, String elementId, String formId, List<Map<String, Object>> fieldList) {
        ReturnVO result = null;
        JSONObject formDescJson = new JSONObject();
        for (Map<String, Object> fieldMap : fieldList) {
            String field = fieldMap.get("field").toString();
            Object fieldState = fieldMap.get("state");
            formDescJson.put(field, fieldState);
        }
        FlwFormNodeset flwFormNodeset = new FlwFormNodeset();
        flwFormNodeset.setFormDesc(formDescJson.toString());
        UpdateWrapper<FlwFormNodeset> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("process_key", processKey)
                .eq("element_id", elementId)
                .eq("form_id", formId);
        int update = flwFormNodeSetMapper.update(flwFormNodeset, updateWrapper);
        if (update > 0) {
            result = new ReturnVO(ReturnCode.SUCCESS, "更新成功", update);
        } else {
            result = new ReturnVO(ReturnCode.FAIL, "更新失败", update);
        }
        return result;
    }

    @Override
    public ReturnVO getInfoByProcessKeyAndType(String processKey, Integer formType) {
        ReturnVO result = null;
        List<FormInfo> formInfos = flwFormNodeSetMapper.selectInfoByKeyAndType(processKey, formType);
        if (!CollectionUtils.isEmpty(formInfos)) {
            result = new ReturnVO(ReturnCode.SUCCESS, "ok", formInfos.get(0));
        } else {
            String msg = "";
            if (formType == 1) {
                msg = "还未分配主表";
            } else {
                msg = "还未分配明细表";
            }
            result = new ReturnVO(ReturnCode.FAIL, msg);
        }
        return result;
    }
}
